import { ChatCompletion, ChatCompletionMessageParam } from "openai/resources/chat/completions.mjs";

export class MessageQueue {
    private historyMessages: (ChatCompletionMessageParam | ChatCompletion)[] = [];
    private readonly maxSize: number = 20;

    constructor(maxSize: number = 20) {
        this.maxSize = maxSize;
    }

    // 添加消息到队列
    public enqueue(message: ChatCompletionMessageParam | ChatCompletion): void {
        // 如果队列已满，删除最旧的消息
        if (this.historyMessages.length >= this.maxSize) {
        this.historyMessages.shift(); // 移除数组第一个元素（最旧的消息）
        }
        // 添加新消息到队列末尾
        this.historyMessages.push(message);
    }

    // 获取所有消息
    public getMessages(): (ChatCompletionMessageParam | ChatCompletion)[] {
        return [...this.historyMessages]; // 返回副本以避免外部修改
    }

    // 清空消息队列
    public clear(): void {
        this.historyMessages = [];
    }

    // 获取队列当前长度
    public get length(): number {
        return this.historyMessages.length;
    }
}
  
// 使用示例
const messageQueue = new MessageQueue();

// 添加消息
messageQueue.enqueue({ role: "user", content: "Hello" });
messageQueue.enqueue({ role: "assistant", content: "How can I help you?" });

// 获取所有消息
const messages = messageQueue.getMessages();

// 处理大量消息时自动保持最近的20条
for (let i = 0; i < 30; i++) {
messageQueue.enqueue({ 
    role: i % 2 === 0 ? "user" : "assistant", 
    content: `Message ${i}` 
});
}
// 此时队列中只有最近的20条消息
console.log(messageQueue.length); // 输出: 20
